package uk.co.richardwkirk.parkrun.data.events;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.co.richardwkirk.parkrun.data.ParkrunDataLoadException;
import uk.co.richardwkirk.parkrun.data.athletes.AthleteSummary;
import uk.co.richardwkirk.parkrun.web.ParkrunPageLoader;

public class ParkrunIndex {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ParkrunIndex pIndex = new ParkrunIndex();
		
		InputStreamReader converter = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(converter);
		
		boolean stopped = false;
		String input = null;
		while (!stopped) {
			try {
				System.out.print("Enter athlete number: ");
				input = in.readLine();

				if (input.equals("q")) {
					stopped = true;
				}
				else if (input.equals("most")) {
					pIndex.allMostEvents();
				}
				else if (input.equals("known")) {
					pIndex.knownPeople();
				}
				else {
					int athleteNumber = Integer.parseInt(input);
					pIndex.showAthlete(athleteNumber);
				}
			}
			catch (NumberFormatException e) {
				System.err.println("Invalid athlete number: " + input);
				System.err.println("Please enter an integer or q to quit.");
			}
			catch (IOException e1) {
				System.err.println("Failed to read from command line.");
				e1.printStackTrace(System.err);
				stopped = true;
			} catch (ParkrunDataLoadException e) {
				System.err.println("Failed to process athlete.");
				e.printStackTrace(System.err);
			}
		}

	}

	private void knownPeople() throws ParkrunDataLoadException {
		List<Integer> knownPeople = new LinkedList<Integer>();
		knownPeople.add(21400); // RWK
		knownPeople.add(21408); // Vicki
		knownPeople.add(31873); // Andrew
		knownPeople.add(31872); // Jenny
		knownPeople.add(33277); // Shiv
		knownPeople.add(398767); // Rob
		showAthletes(knownPeople);
	}

	private void showAthletes(List<Integer> athleteList) throws ParkrunDataLoadException {
		int maxPIndex = 0;
		LinkedList<String> maxPIndexPeople = new LinkedList<String>();
		for (Integer athleteNumber : athleteList) {
			AthleteSummary athlete = AthleteSummary.loadAthleteSummary(athleteNumber);
			System.out.println(athlete.summaryLine());
			
			int pIndex = athlete.parkrunIndex();
			if (pIndex > maxPIndex) {
				maxPIndexPeople.clear();
				maxPIndex = pIndex;
			}
			
			if (pIndex == maxPIndex) {
				maxPIndexPeople.add(athlete.getShortParkrunIndexBreakDown());
			}
			
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// Ignore
			}
		}
		
		System.out.println("------------------------------------------------------");
		System.out.println("Looked at " + athleteList.size() + " athletes.");
		System.out.println("Max pIndex is = " + String.valueOf(maxPIndex));
		System.out.println("Held by " + String.valueOf(maxPIndexPeople.size()) + " people:");
		for (String name : maxPIndexPeople) {
			System.out.print(" - ");
			System.out.println(name);
		}
		System.out.println("------------------------------------------------------");
	}

	private void allMostEvents() throws ParkrunDataLoadException {
		String mostEventsURL = "http://www.parkrun.org.uk/results/mostevents/";
		ParkrunPageLoader pageLoader = new ParkrunPageLoader();
		String mostEventsContent = pageLoader.load(mostEventsURL);
		List<Integer> allAthletes = getAthleteSet(mostEventsContent);
		showAthletes(allAthletes);		
	}

	private List<Integer> getAthleteSet(String mostEventsContent) {
		List<Integer> allAthletes = new LinkedList<Integer>();
		Pattern athletePattern = Pattern.compile("athleteNumber=\\d+");
		Matcher athleteMatcher = athletePattern.matcher(mostEventsContent);
		while (athleteMatcher.find()) {
			String athleteNumber = athleteMatcher.group().substring(athleteMatcher.group().indexOf('=')+1);
			allAthletes.add(Integer.parseInt(athleteNumber));
		}
		return allAthletes;
	}

	private void showAthlete(int athleteNumber) throws ParkrunDataLoadException  {
		AthleteSummary athlete = AthleteSummary.loadAthleteSummary(athleteNumber);
		System.out.println(athlete.summaryLine());
	}

}
